package com.microservices.yucloud.api.mongo.service;

import com.microservices.yucloud.api.mongo.dao.UserDao;
import com.microservices.yucloud.api.mongo.entity.UserEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zy
 * @date 2019-08-20 17:55
 **/
@Slf4j
@Service
public class UserService {

    @Resource
    private UserDao userDao;

    public void save(UserEntry userEntry) {
        userEntry.setCreateDate(new Date());
        userEntry.setLastModifyDate(new Date());
        UserEntry user = userDao.save(userEntry);
        log.info("保存成功[{}]", user);
    }

    public void update(UserEntry userEntry) {
        userEntry.setLastModifyDate(new Date());
        Query query = new Query(Criteria.where("id").is(userEntry.getId()));
        Update update = new Update().set("name", userEntry.getName()).set("password", userEntry.getPassword());
        userDao.updateFirst(query, update);
    }

    public List<UserEntry> findAll() {
        return userDao.findAll();
    }

    public UserEntry findByName(String name) {
        Query query = new Query(Criteria.where("name").is(name));
        return userDao.findOne(query);
    }

}
